from datetime import datetime
from datetime import timedelta
from datetime import timezone
print(datetime.now())  # 输出当前时间
# ----------写入指定时间------------
dt = datetime(2012, 12, 21, 00, 00)
print(dt)
# -----------将时间转换为时间戳-----
# Python的timestamp是一个浮点数,数位表示毫秒数。某些编程语言（如Java和JavaScript）的timestamp使用整数表示毫秒数，
# 这种情况下只需要把timestamp除以1000就得到Python的浮点表示方法。
print(dt.timestamp())
print(datetime.now().timestamp())
# ----------将时间戳转换为时间-----
dts = datetime(2008, 8, 18, 8, 18, 28).timestamp()
print(dts)
print(datetime.fromtimestamp(dts))
print(datetime.utcfromtimestamp(dts))
# --------------str2datetime----
print(datetime.strptime("2015-6-1 18:30:15", "%Y-%m-%d %H:%M:%S"))
# --------------datetime2str----
print(datetime.now().strftime("%a %b %d %H %M"))
# --------------datetime换算----
dtn = datetime.now()
print(dtn + timedelta(days=1))
print(dtn - timedelta(hours=10))
print(dtn - timedelta(days=2, hours=3, weeks=1))
# --------------本地时间转换为UTC-----
tz_utc_8 = timezone(timedelta(hours=8))  # 创建时区UTC+8:00
now = datetime.now()
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))
# ---------时区转换-------------------
# 拿到UTC时间，并强制设置时区为UTC+0:00:
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
# astimezone()将转换时区为北京时间:
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(bj_dt)
# astimezone()将转换时区为东京时间:
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)
# astimezone()将bj_dt转换时区为东京时间:
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt2)